<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { QForm } from '@meetjs/element-plus-kit'
import { useUserStore } from '@/store/user'

import { basicFormOptions, unitChangeFormOptions, projectChangeFormOptions } from './formConfig'
import StepNavigation from './components/StepNavigation.vue'
import CommonUpload from './components/commonUpload.vue'
import mgzPlaceholder from '@/assets/athlete/icons/mgzPlaceholder.png'
import certiPlaceholder from '@/assets/athlete/icons/certiPlaceholder.png'
import otherPlaceholder from '@/assets/athlete/icons/otherPlaceholder.png'
import idFrontPlaceholder from '@/assets/athlete/icons/idFront.png'
import idBackPlaceholder from '@/assets/athlete/icons/idBack.png'
import idValidate from '@/assets/athlete/icons/idValidate.svg'
import faceValidate from '@/assets/athlete/icons/faceIdValidate.svg'
import fingerprintValidate from '@/assets/athlete/icons/fingerprintValidate.svg'
import fileIcon from '@/assets/athlete/detail/file.png?url'
import { createAthleteChangeApi } from '@/api/athlete/index'
import { type AthleteViewModel } from '@/api/athlete/transformer'
import { ChangeType } from '@/api/athlete/change/types'

// 身份验证列表项类型
interface AuthListItem {
	img: string
	title: string
	description: string
	validateStatus: number
	unValidate: string
	validated: string
	type: 'identity' | 'face' | 'fingerprint'
	verifyKey: 'verifyIdentity' | 'verifyFace' | 'verifyFingerprint'
}

// Store
const userStore = useUserStore()
const curAthlete = userStore.userInfo.athlete

const validating = ref(false)
const submitting = ref(false)

// 步骤配置
const steps = [
	{
		title: '基本信息确认',
		description: '请确认基本注册信息'
	},
	{
		title: '资质信息',
		description: '填报变更信息并上传材料'
	},
	{
		title: '提交申请',
		description: '确认无误后提交'
	}
]

// 表单数据
const registerForm = ref<Partial<AthleteViewModel>>({})

// 变更信息数据
const changeType = ref<ChangeType>(ChangeType.ORG_CHANGE) // 变更类型

type changeForm = {
	changeBefore: number | undefined
	changeAfter: number | undefined
}
const unitChangeForm = ref<changeForm>({
	changeBefore: undefined,
	changeAfter: undefined
})
const projectChangeForm = ref<changeForm>({
	changeBefore: undefined,
	changeAfter: undefined
})

// 协议确认
const agreementChecked = reactive({
	info: false,
	privacy: false
})

// 表单引用
const basicFormRef = ref()
const unitChangeFormRef = ref({})
const projectChangeFormRef = ref({})

const isFieldFilled = (value: any) => {
	if (value === null || value === undefined) return false
	if (typeof value === 'string') return value.trim() !== ''
	if (typeof value === 'number') return value > 0
	return Boolean(value)
}

const step2Complete = computed(() => {
	// 只检查变更信息是否完整，暂时不需要资质材料
	const changeInfoComplete = (() => {
		// 变更类型必须选择
		if (!changeType.value) {
			console.log('变更类型未选择')
			return false
		}

		// 单位变更：变更前后单位都必须填写
		if (changeType.value === ChangeType.ORG_CHANGE) {
			return unitChangeForm.value.changeAfter
		}
		// 项目变更：变更前后项目都必须填写
		else if (changeType.value === ChangeType.PROJECT_CHANGE) {
			return projectChangeForm.value.changeAfter
		}

		return false
	})()

	return changeInfoComplete
})

const currentStep = computed(() => {
	// 简化步骤：只需要检查变更信息
	if (!step2Complete.value) return 2
	return 3
})

const canSubmit = computed(() => {
	// 只需要变更信息完整 + 协议确认
	return step2Complete.value && agreementChecked.info && agreementChecked.privacy
})

const authList = ref<AuthListItem[]>([
	{
		img: idValidate,
		title: '身份验证',
		description: '系统将自动验证您的身份证信息真实性',
		validateStatus: 0,
		unValidate: '开始验证',
		validated: '已验证',
		type: 'identity',
		verifyKey: 'verifyIdentity'
	},
	{
		img: faceValidate,
		title: '人脸识别',
		description: '将您的照片与身份证照片进行比对验证',
		validateStatus: 0,
		unValidate: '开始识别',
		validated: '已识别',
		type: 'face',
		verifyKey: 'verifyFace'
	},
	{
		img: fingerprintValidate,
		title: '指纹录入',
		description: '录入指纹信息，确保身份的唯一性',
		validateStatus: 0,
		unValidate: '录入指纹',
		validated: '已录入',
		type: 'fingerprint',
		verifyKey: 'verifyFingerprint'
	}
])

// 证件审核记录资料
const auditRecords = ref([
	{
		id: 1,
		title: '注册审核中',
		operator: '审核员A',
		description: '请等待审核员审核',
		time: '2024-09-09'
	}
])

// 验证处理函数
const handleVerify = async (type: 'identity' | 'face' | 'fingerprint') => {
	try {
		validating.value = true

		// 模拟验证API调用
		await new Promise(resolve => setTimeout(resolve, 1500))

		// 更新表单验证状态
		if (type === 'identity') {
			registerForm.value.verifyIdentity = 1 // 1=已验证, 0=未验证
			ElMessage.success('身份验证成功')
		} else if (type === 'face') {
			registerForm.value.verifyFace = 1 // 1=已验证, 0=未验证
			ElMessage.success('人脸识别成功')
		} else if (type === 'fingerprint') {
			registerForm.value.verifyFingerprint = 1 // 1=已验证, 0=未验证
			ElMessage.success('指纹录入成功')
		}

		// 更新 authList 中的验证状态
		const authItem = authList.value.find(item => item.type === type)
		if (authItem) {
			authItem.validateStatus = 1
		}
	} catch (error) {
		ElMessage.error('验证失败，请重试')
	} finally {
		validating.value = false
	}
}

const isSubmit = ref(false)

const handleSubmit = async () => {
	try {
		submitting.value = true

		// 验证变更类型必须选择
		if (!changeType.value) {
			ElMessage.error('请选择变更类型')
			return
		}

		// 获取运动员ID
		if (!curAthlete?.id) {
			ElMessage.error('未能获取运动员信息，请重新登录')
			return
		}

		// 构建变更申请数据
		let changeAfter: number | undefined

		// 根据变更类型获取变更后的值
		if (changeType.value === ChangeType.ORG_CHANGE) {
			changeAfter = unitChangeForm.value.changeAfter || undefined
		} else if (changeType.value === ChangeType.PROJECT_CHANGE) {
			changeAfter = projectChangeForm.value.changeAfter || undefined
		}

		const submitData = {
			infoId: Number(curAthlete.id),
			changeType: changeType.value,
			changeAfter
		}

		console.log('提交变更申请数据:', submitData)

		// 调用变更申请API
		const res = await createAthleteChangeApi(submitData)

		if (res.code === 200) {
			ElMessage.success('变更申请提交成功，请等待审核')
			isSubmit.value = true
		}
	} catch (error) {
		ElMessage.error('表单验证失败，请检查必填项')
	} finally {
		submitting.value = false
	}
}

// 变更类型改变处理
const handleChangeTypeChange = () => {
	// 清空之前的表单数据
	unitChangeForm.value = {
		changeBefore: curAthlete?.registerOrgId || undefined,
		changeAfter: undefined
	}
	projectChangeForm.value = {
		changeBefore: curAthlete?.registerProject || undefined,
		changeAfter: undefined
	}
}

const checkUserStatus = () => {
	if (curAthlete) {
		registerForm.value = {
			...curAthlete,
			registerYear: String(curAthlete.registerYear)
		}
	}
}

// 初始化
onMounted(async () => {
	// 检查用户状态，判断是否需要年度确认 和 是否 已经提交注册
	checkUserStatus()
	console.log('registerForm.value:', registerForm.value)
})
</script>

<template>
	<div class="athlete-register-page">
		<!-- 标题 -->
		<div class="bg-primary flex flex-col items-center justify-center pt-5">
			<div class="text-2xl text-primary font-500 mb-3">运动员变更申请</div>
			<div class="text-sm text-foreground-tertiary">请按步骤完整填写信息，确保信息真实有效</div>
		</div>
		<!-- 步骤导航 -->
		<StepNavigation
			:current-step="currentStep"
			:steps="steps"
		/>

		<!-- 证件审核记录资料 -->
		<div
			v-if="isSubmit"
			class="p-5 bg-primary rounded mb-4"
		>
			<div class="text-base text-primary font-500 mb-4">证件审核记录资料</div>
			<div class="flex flex-col gap-6">
				<div
					v-for="record in auditRecords"
					:key="record.id"
					class="relative"
				>
					<!-- 时间线 -->
					<div class="flex gap-4">
						<!-- 左侧图标和线 -->
						<div class="flex flex-col items-center">
							<img
								:src="fileIcon"
								class="size-6 object-fill"
							/>
							<div class="w-px bg-light flex-1 mt-2" />
						</div>
						<!-- 右侧内容 -->
						<div class="flex-1 pb-2">
							<div class="flex items-center justify-between mb-2">
								<div class="text-primary font-500">{{ record.title }}</div>
								<div class="text-secondary text-sm">{{ record.time }}</div>
							</div>
							<div class="text-secondary text-sm mb-0.5">操作人：{{ record.operator }}</div>
							<div class="text-secondary text-sm">{{ record.description }}</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="mx-auto bg-primary">
			<!-- 表单内容区 -->
			<div class="mx-auto w-[866px] p-6 min-h-[800px]">
				<!-- 基本信息步骤 -->
				<div class="step-content">
					<h3 class="text-primary text-lg font-semibold mb-6">基本信息</h3>

					<!-- 身份证照片上传区（独立组件） -->
					<div>
						<div class="flex items-start gap-1 mb-4">
							<span class="text-danger text-sm">*</span>
							<label class="text-foreground-primary text-sm font-medium">
								身份证正面照片
								<span class="text-foreground-tertiary text-xs ml-2"> pdf, png, jpg 可以上传, 图片大小不能超过 100MB </span>
							</label>
						</div>
						<!-- 上传区域容器 -->
						<div class="flex gap-6">
							<!-- 身份证正面上传 -->
							<div class="flex-1">
								<CommonUpload
									v-model="registerForm.identityFront"
									disabled
									:placeholder-src="idFrontPlaceholder"
									width="312px"
									height="198px"
								/>
							</div>

							<!-- 身份证背面上传 -->
							<div class="flex-1">
								<CommonUpload
									v-model="registerForm.identityBack"
									disabled
									:placeholder-src="idBackPlaceholder"
									width="312px"
									height="198px"
								/>
							</div>
						</div>
					</div>

					<!-- QForm 表单区域 -->
					<QForm
						ref="basicFormRef"
						:model="registerForm"
						:form-options="basicFormOptions"
						:label-position="'top'"
						:col="12"
						:gutter="36"
						disabled
						label-width="120px"
						class="athlete-basic-form"
					/>
				</div>

				<!-- 资质信息步骤 -->
				<div class="step-content">
					<h3 class="text-primary text-lg font-semibold mb-6">资质信息</h3>

					<!-- 近期免冠照片上传 -->
					<div class="mb-8">
						<div class="flex items-start gap-1 mb-4">
							<span class="text-danger text-sm">*</span>
							<label class="text-foreground-primary text-sm font-medium">
								上传近期免冠照片
								<span class="text-foreground-tertiary text-xs ml-2"> 用于人脸识别验证，要求正面、清晰 </span>
							</label>
						</div>
						<CommonUpload
							v-model="registerForm.personPhoto"
							disabled
							:placeholder-src="mgzPlaceholder"
							width="136px"
							height="182px"
						/>
					</div>

					<!-- 资质证书上传 -->
					<div class="mb-8">
						<div class="flex items-start gap-1 mb-4">
							<span class="text-danger text-sm">*</span>
							<label class="text-foreground-primary text-sm font-medium">
								运动员资质证书
								<span class="text-foreground-tertiary text-xs ml-2"> 最多可上传3张，要求正面、清晰 </span>
							</label>
						</div>

						<CommonUpload
							v-model="registerForm.qualifications"
							disabled
							:placeholder-src="certiPlaceholder"
							:max-count="3"
							is-array
							width="155px"
							height="116px"
						/>
					</div>

					<!-- 其他证明材料上传 -->
					<div class="mb-8">
						<div class="flex items-start gap-1 mb-4">
							<span class="text-danger text-sm">*</span>
							<label class="text-foreground-primary text-sm font-medium">
								其他相关证明
								<span class="text-foreground-tertiary text-xs ml-2"> 最多可上传9张，如体检报告、学籍证明等 </span>
							</label>
						</div>
						<div class="w-[600px]">
							<CommonUpload
								v-model="registerForm.otherMaterial"
								disabled
								:placeholder-src="otherPlaceholder"
								:max-count="9"
								is-array
								width="155px"
								height="116px"
							/>
						</div>
					</div>
				</div>

				<!-- 变更信息 -->
				<div class="step-content">
					<h3 class="text-primary text-lg font-semibold mb-6">变更信息</h3>

					<!-- 变更类型选择 -->
					<div class="mb-6">
						<div class="flex items-start gap-1 mb-4">
							<span class="text-danger text-sm">*</span>
							<label class="text-foreground-primary text-sm font-medium"> 变更类型 </label>
						</div>
						<el-select
							v-model="changeType"
							:disabled="isSubmit"
							placeholder="请选择变更类型"
							clearable
							style="width: 200px"
							@change="handleChangeTypeChange"
						>
							<el-option
								label="单位变更"
								:value="1"
							/>
							<el-option
								label="项目变更"
								:value="2"
							/>
						</el-select>
					</div>
					<div
						v-if="changeType === ChangeType.ORG_CHANGE"
						class="mb-8"
					>
						<QForm
							ref="unitChangeFormRef"
							:model="unitChangeForm"
							:form-options="unitChangeFormOptions"
							:label-position="'top'"
							:col="12"
							:gutter="36"
							:disabled="isSubmit"
							label-width="120px"
							class="change-form"
						/>
					</div>

					<!-- 项目变更表单 -->
					<div
						v-if="changeType === ChangeType.PROJECT_CHANGE"
						class="mb-8"
					>
						<QForm
							ref="projectChangeFormRef"
							:model="projectChangeForm"
							:form-options="projectChangeFormOptions"
							:label-position="'top'"
							:col="12"
							:gutter="36"
							:disabled="isSubmit"
							label-width="120px"
							class="change-form"
						/>
					</div>
				</div>

				<!-- 身份验证步骤 -->
				<div class="step-content">
					<h3 class="text-primary text-lg font-semibold mb-6">身份验证</h3>

					<!-- 认证操作区域 -->
					<div class="bg-white rounded-lg flex flex-col gap-4 space-y-0">
						<div
							v-for="item in authList"
							:key="item.title"
							class="flex items-center rounded justify-between px-4 py-5 border border-background-tertiary hover:shadow-[0px_2px_5px_0px_rgba(0,0,0,0.1)] transition-all duration-300"
						>
							<!-- 左侧图标和信息 -->
							<div class="flex gap-4">
								<img
									:src="item.img"
									class="size-[30px] item-start"
									alt=""
								/>
								<div class="flex-1">
									<h4 class="text-gray-900 font-medium text-base mb-1">
										{{ item.title }}
									</h4>
									<p class="text-gray-500 text-sm">
										{{ item.description }}
									</p>
								</div>
							</div>

							<!-- 右侧操作按钮 -->
							<div class="flex items-center">
								<!-- 未验证状态 -->
								<el-button
									v-if="item.validateStatus === 0"
									size="default"
									plain
									:loading="validating"
									class="px-6 py-2"
									@click="handleVerify(item.type)"
								>
									{{ item.unValidate }}
								</el-button>

								<!-- 已验证状态 -->
								<div
									v-else
									class="flex items-center gap-2 px-4 py-2 bg-green-50 text-green-600 rounded-md border border-green-200"
								>
									<svg
										class="w-4 h-4"
										fill="currentColor"
										viewBox="0 0 20 20"
									>
										<path
											fill-rule="evenodd"
											d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
											clip-rule="evenodd"
										/>
									</svg>
									<span class="text-sm font-medium">
										{{ item.validated }}
									</span>
								</div>
							</div>
						</div>
					</div>

					<!-- 申请确认 -->
					<div class="bg-background-secondary border rounded p-4 mt-6">
						<h4 class="text-primary text-base font-medium mb-4">申请确认</h4>
						<div class="space-y-1">
							<el-checkbox
								v-model="agreementChecked.info"
								class="confirm"
								label="我确认以上填写的所有信息真实有效，如有虚假信息愿承担相应责任"
							/>
							<el-checkbox
								v-model="agreementChecked.privacy"
								class="confirm"
								label="我同意将个人信息用于运动员注册管理，并接受相关公示要求"
							/>
						</div>
					</div>
				</div>

				<!-- 分割线 -->
				<div class="h-[1px] bg-background-tertiary my-6" />

				<!-- 底部操作按钮 -->
				<div class="flex justify-end">
					<el-button
						type="primary"
						size="large"
						:loading="submitting"
						:disabled="!canSubmit || isSubmit"
						@click="handleSubmit"
					>
						提交申请
					</el-button>
				</div>
			</div>
		</div>
	</div>
</template>

<style lang="scss" scoped>
.step-content {
	animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(10px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}
.confirm {
	:deep(.el-checkbox__label) {
		color: #606266;
	}
}
</style>
